<!--表格列表页面组件--业务-->
<template>
    <el-container class="layout-container" v-loading="pageLoading">

        <el-header class="layout-header">

            <div class="title-wrap" v-if="option.titleList && option.titleList.length">
                <table>
                    <tr>
                        <td v-for="item in option.titleList" class="title-item" :class="{active: router.currentRoute.value.path === item.path}"
                            @click="router.push(item.path)">{{item.name}}</td>
                    </tr>
                </table>
            </div>

            <div class="btns-wrap">

                <div class="h-left">
                    <slot name="hLSlot"></slot>

                    <template v-for="item in config.hLBtns">
                        <slot v-if="item.useSlot" :name="item.slotName"></slot>
                        <el-button v-else :type="item.type" @click="item.event" :data-id="item.id">{{item.title}}</el-button>
                    </template>
                </div>
                <div class="h-right">
                    <template v-for="item in config.hRBtns">
                        <slot v-if="item.useSlot" :name="item.slotName"></slot>
                        <el-button v-else :type="item.type" @click="item.event" :data-id="item.id">{{item.title}}</el-button>
                    </template>
                    <el-button v-if="config.showCondition" type="primary" @click="search">查询</el-button>
                    <el-button v-if="config.showCondition" type="default" @click="reset">重置</el-button>
                    <slot name="rightBtn"></slot>
                </div>

            </div>
        </el-header>

        <el-main class="layout-main">
            <!--搜索条件-->
            <m-condition
                    v-bind="$attrs"
                    v-if="config.showCondition"
                    class="condition-wrap"
                    ref="conditionRef" :fields="config.conditions"
                    @search="search"
                    @resize="setTableHeight"/>
            <!--表格-->
            <div class="table-wrap" ref="tableRef" v-loading="tableLoading">
                <el-table
                        ref="tRef"
                        v-bind="$attrs"
                        class="table-auto"
                        :height="tableHeight + 'px'"
                        border
                        :data="tableData"
                        highlight-current-row
                        :tooltip-options="{placement: 'right'}"
                        empty-text="暂无数据"
                >

                    <el-table-column v-if="config.tableSelection" type="selection" width="55" />
                    <el-table-column v-for="item in config.cols"
                                     :prop="item.prop" :label="item.label"
                                     min-width="130" :width="columnWidth[item.prop]"
                                     :show-overflow-tooltip="option.showOverflowTooltip"
                                     :fixed="item.fixed"
                                     :sortable="item.sortable"
                    >
                        <template #header="scope" v-if="item.customSort">
                            <div class="sort-header" @click="sortData(scope)">
                                {{scope.column.label}}
                                <div class="caret-wrapper" :class="sortOption.sortField.includes(scope.column.property) ? sortOption.sortType === 'asc' ? 'ascending' : sortOption.sortType === 'desc' ? 'descending' : '' : ''">
                                    <i class="sort-caret ascending"></i>
                                    <i class="sort-caret descending"></i>
                                </div>
                            </div>
                        </template>
                        <template #default="scope">
                            <component v-if="item.component" :is="item.component" v-bind="item.attrs(scope)"></component>
                            <!--<component v-if="item.component" :is="item.templet(scope)"></component>-->
                            <div v-else-if="item.templte" v-html="item.templte(scope)"></div>
                            <div v-else-if="item.type === 'bool'">{{scope.row[item.prop] ? '是' : '否'}}</div>
                            <div v-else-if="['date','datetime'].includes(item.type)">{{scope.row[item.prop] && crtTimeFtt(new Date(scope.row[item.prop]),item.format)}}</div>
                            <div v-else-if="item.type === 'picture'">
                                <el-image
                                        v-if="scope.row[item.prop] && !item.hidePic"
                                        style="width: 80px; height: 60px"
                                        :src="getPictureList(scope.row[item.prop])[0]"
                                        :zoom-rate="1.2"
                                        :preview-src-list="getPictureList(scope.row[item.prop])"
                                        :initial-index="0"
                                        :z-index="4"
                                        hide-on-click-modal
                                        fit="cover"
                                        preview-teleported
                                />
                                <!--默认不显示照片，点击按钮才显示-->
                                <el-button v-if="scope.row[item.prop] && item.hidePic"
                                link type="primary" @click.stop="onPreview(scope.row[item.prop])">查看</el-button>
                            </div>
                            <template v-else>{{scope.row[item.prop]}}</template>
                        </template>
                    </el-table-column>


                    <el-table-column fixed="right" label="操作" min-width="160" v-if="config.colBtns.length > 0" :width="columnWidth['operate']">
                        <template #default="scope">
                            <template v-for="item in config.colBtns">
                                <el-button
                                        v-if="item.filterMethod ? item.filterMethod(scope) : true"
                                        link :type="item.type" @click.stop="item.event && item.event(scope,item.id)">{{item.title}}</el-button>
                            </template>

                            <!--<el-button link type="danger" @click="handleClick(scope,'edit')">删除</el-button>-->
                            <!--<el-button link type="warning" @click="handleClick(scope,'del')">复制</el-button>-->
                        </template>
                    </el-table-column>
                </el-table>
            </div>

        </el-main>
        <el-footer class="layout-footer">
            <!--统计-->
            <div class="total-wrap" >
                <template v-if="config.showTotal">

                    统计：
                    <div class="total-item" v-for="item in total">
                        <span class="item-label">{{item.title}}</span>
                        <span class="item-value">{{item.value}}</span>
                    </div>
                </template>


            </div>
            <!--分页-->
            <div class="page-wrap">
                <m-page
                        v-if="config.showPage"
                        v-model:current-page="$attrs.page.currentPage"
                        v-model:page-size="$attrs.page.pageSize"
                        :total="$attrs.page.total"
                />
            </div>
        </el-footer>


        <el-image-viewer v-if="previewShow"
                         :url-list="previewList"
                         hide-on-click-modal
                         :initial-index="initialIndex"
                         @close="closePreview"
        ></el-image-viewer>

    </el-container>
</template>

<script setup>
    import {ref,reactive,watch,defineProps,defineEmits} from 'vue';
    import { useRouter} from 'vue-router'

    // const http = process.env.VUE_APP_PATH;
    const http = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_PATH : window.webConfig.webApiBasePath;

    //组件
    import MCondition from '@/components/common/Condition/Condition'
    import MPage from '@/components/common/Page/Page'

    import { useTable } from '@/composables/table'

    let router = useRouter();

    import {crtTimeFtt} from '@/utils/utils'

    const props = defineProps(['option','total','tableData','tableLoading','pageLoading']),
      emit = defineEmits(['searchData','pageChange','colBtnClick','sortData']);


    let {tableHeight,tableRef,cols,columnWidth,setTableHeight,setColumnWidth} = useTable();

    let dflOption = {
      hLBtns: [],
      hRBtns: [],

      //条件
      showCondition: false,
      conditions:[],

      //表格
      cols: [],
      colBtns: [],

      //分页
      showPage: false,

      //统计
      showTotal: false,
      totalItem: []

    },
      config = reactive({}),
      conditionRef = ref(null),
      tRef = ref(null);


    //监听
    watch(props.option, (val)=>{
      config = {...dflOption,...val}
    },{immediate: true});

    //监听表格数据变化，自适应列宽
    watch(() => props.tableData, (val)=>{
      setColumnWidth(val,config.cols,config.colBtns)
    })

    //搜索，组件内触发搜索（调用页面主动触发时是用双向绑定）
    function search(){
      let query = conditionRef.value.query;
      emit('searchData',query);
    }
    //重置搜索条件
    function reset() {
      conditionRef.value.reset();
      emit('searchData',{});
    }


    //预览图片
    let previewShow = ref(false),
      previewList = reactive([]),
      initialIndex = ref(0);

    //格式图片地址
    function getPictureList(str){
        let list = [],
          arr = str.split(',');
      arr.forEach(item => list.push(http + item));
      return list
    }
    //预览图片
    function onPreview(fileStr) {
      previewShow.value = true;
      previewList = getPictureList(fileStr)
    }
    //关闭预览
    function closePreview() {
      previewShow.value = false;
    }

    //排序参数，sortField排序字段，sortType排序类型【asc，desc，null空】
    let sortOption = reactive({
      sortField: [],
      sortType: ''
    })
    //排序：当前排序只适用于单个字段排序
    function sortData(scope){
      let {property} = scope.column;
      let type = '';
      if (sortOption.sortField.includes(property)){
        switch (sortOption.sortType) {
          case 'asc':
            type = 'desc';
            break;
          case 'desc':
            type = '';
            break;
          default:
            type = 'asc';
        }
      }else {
        sortOption.sortField = [property];
        type = 'asc'
      }
      sortOption.sortType = type;
      let query = {
        orderBy: `${property} ${sortOption.sortType}`
      }
      emit('sortData',type ? query : '');
    }


    defineExpose({getSelectionRows: () => tRef.value.getSelectionRows()})
</script>

<style scoped lang="less">
    @import '../../assets/css/pageList.less';
</style>
